package com.mj.listen1._12_堆.heap;

import com.mj.listen1._12_堆.printer.BinaryTreeInfo;

import java.util.Comparator;

/**
 * 堆结构的顶层抽象
 *
 * @param <E>
 */
public abstract class AbstractHeap<E> implements Heap<E>, BinaryTreeInfo {
    protected int size;
    protected Comparator<E> comparator;

    public AbstractHeap(Comparator<E> comparator) {
        this.comparator = comparator;
    }

    public AbstractHeap() {
        this(null);
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    protected int compare(E e1, E e2) {
        if (comparator != null) {
            return comparator.compare(e1, e2);
        }
        return ((Comparable<E>) e1).compareTo(e2);
    }

    protected void emptyCheck() {
        if (size == 0)
            throw new IndexOutOfBoundsException("Heap is empty");
    }
}
